package com.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * 功能:
 * Version: 1.0
 * Author: DR.YangLong
 * Date: 2014/7/20
 * Time: 13:08
 * Email:410357434@163.com
 * Editor:
 */
@Controller
@RequestMapping("/shiro")
public class ShiroController {

    @RequestMapping("/login.action")
    public String userLogin(HttpServletRequest req, Model model) {
        String exceptionClassName = (String) req.getAttribute("shiroLoginFailure");
        String error = null;
        String viename = "login";
        if (SecurityUtils.getSubject().isAuthenticated()) {
            viename = "index";
        } else {
            if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
                error = "用户名/密码错误";
            } else if (IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
                error = "用户名/密码错误";
            } else if (exceptionClassName != null) {
                error = "其他错误：" + exceptionClassName;
            }
            model.addAttribute("error", error);
        }
        return viename;
    }

    @RequestMapping("/form.action")
    public
    @ResponseBody
    String form() {
        return "success";
    }

    @RequestMapping("/test.action")
    public
    @ResponseBody
    String testAu() {
        return "success";
    }

    @RequestMapping("/logout")
    public ModelAndView logout() {
        SecurityUtils.getSubject().logout();
        return new ModelAndView("/shiro/login.action");
    }
}
